package com.itheima.demo5.ui;

import com.itheima.demo5.client.Constant;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class RegisterFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JButton registerButton;
    private Socket socket;
    DataInputStream dis;
    DataOutputStream dos;

    public RegisterFrame() {
        try {
            socket = new Socket("127.0.0.1", Constant.PORT);
            dis = new DataInputStream(socket.getInputStream());
            dos = new DataOutputStream(socket.getOutputStream());
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        setTitle("Register");
        setSize(300, 200);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JPanel panel = new JPanel(new GridLayout(3, 2));

        JLabel usernameLabel = new JLabel("Username:");
        usernameField = new JTextField();
        JLabel passwordLabel = new JLabel("Password:");
        passwordField = new JPasswordField();
        registerButton = new JButton("Register");

        panel.add(usernameLabel);
        panel.add(usernameField);
        panel.add(passwordLabel);
        panel.add(passwordField);
        panel.add(registerButton);

        registerButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = usernameField.getText();
                String password = new String(passwordField.getPassword());
                // 这里可以添加注册逻辑
                registerUser(username, password);
            }
        });

        add(panel);
    }

    private void registerUser(String username, String password) {
        // 这里可以添加实际的注册逻辑
        try {
            DataInputStream dis = new DataInputStream(socket.getInputStream());
            DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
            // 1. 登录， 2. 注册
            dos.writeInt(2);
            dos.writeUTF(username);
            dos.writeUTF(password);

            // 接收结果 1 成功， 0 失败
            int result = dis.readInt();
            if(result == 1){
                JOptionPane.showMessageDialog(RegisterFrame.this, "注册成功", "Success", JOptionPane.INFORMATION_MESSAGE);
                this.dispose();
            }
            else{
                JOptionPane.showMessageDialog(RegisterFrame.this, "注册用户已存在", "Error", JOptionPane.ERROR_MESSAGE);
            }
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

